/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package personal.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Map.Entry;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.XMLConstants;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.sax.SAXResult;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.apache.fop.apps.FOUserAgent;
import org.apache.fop.apps.Fop;
import org.apache.fop.apps.FopFactory;
import org.apache.xmlgraphics.util.MimeConstants;
import org.xml.sax.SAXException;
import personal.dao.*;
import personal.obj.*;
import personal.utility.Utility;
import personal.xml.JAXBBookValidationHandler;
import personal.xml.JAXBMarshall;
import personal.xml.StAXParserAPI;

/**
 *
 * @author PHATNBSE61057
 */
public class ProcessServlet extends HttpServlet {

    final String homepage = "Mainpage.jsp";
    final String loginPage = "G_loginPage.jsp";
    final String registerPage = "G_registerPage.jsp";
    final String userNotActivePage = "G_login_userNotActive.jsp";
    final String staffMainPage = "Mainpage_Staff.jsp";
    final String searchResulPage = "G_viewSearchResult.jsp";
    final String staffSearchResult = "S_viewSearchResult.jsp";
    final String productDetailPage = "G_ProductDetail.jsp";
    final String cartPage = "C_viewCartPage.jsp";
    final String ckOutBillingPage = "C_CkOut_Billing.jsp";
    final String ckOutDeliveryPage = "C_CkOut_Delivery.jsp";
    final String ckOutPaymentgPage = "C_CkOut_Payment.jsp";
    final String ckOutConfirmPage = "C_CkOut_Confirm.jsp";
    final String addNewBookPage = "S_addNewBook.jsp";
    final String viewOrderPage = "G_viewOrder.jsp";
    final String viewOrderDetail = "G_viewOrderDetailPage.jsp";

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, SAXException, TransformerConfigurationException, TransformerException {
        response.setContentType("text/html;charset=UTF-8");
//        PrintWriter out = response.getWriter();
        try {
            String action = request.getParameter("btAction");
            //<editor-fold defaultstate="collapsed" desc="LOAD BOOK SECTOR">
            if (action.equals("Load Book")) {
                BookDAO bd = new BookDAO();
                List<Book> listBook = new ArrayList<Book>();
                listBook = bd.getAllBook();

                OrderDAO od = new OrderDAO();
                List<Order> lo = new ArrayList<Order>();
                lo = od.getOrderByUsername("kha");

                if (listBook != null) {
                    System.out.println("Have Book");
                }
                HttpSession session = request.getSession();
//                session.setAttribute("LISTBOOK", listBook);
                session.setAttribute("LISTBOOK", lo);
                request.getRequestDispatcher("homepage.jsp").forward(request, response);
            } //</editor-fold>
            //====================================================================//
            //<editor-fold defaultstate="collapsed" desc="LOGIN SECTOR">
            else if (action.equalsIgnoreCase("Login")) {
                String username = request.getParameter("txtUsername");
                String password = request.getParameter("txtPassword");
                User user = new User();
                UserDAO uDAO = new UserDAO();
                user = uDAO.checkLogin(username, password);

                if (user != null) {
                    RoleDAO roleD = new RoleDAO();
                    boolean isStaff = false;
                    String roleName = roleD.getRoleNameByID(user.getRoleID());

                    if (roleName.equalsIgnoreCase("Staff")) {
                        isStaff = true;
                    }
                    HttpSession session = request.getSession();
                    session.setAttribute("USER", user);
                    /**
                     * Case 1: user not active -> redirect to error page Case 2:
                     * user is staff -> redirect to staff main page Case 3: user
                     * is customer -> redirect to homepage
                     */
                    if (!user.isIsActive()) {
                        request.getRequestDispatcher(userNotActivePage).forward(request, response);
                    } else if (isStaff) {
                        request.getRequestDispatcher(staffMainPage).forward(request, response);
                    } else {
                        request.getRequestDispatcher(homepage).forward(request, response);
                    }
                } else {
                    String error = "Error";
                    request.setAttribute("ERROR", error);
                    request.getRequestDispatcher(loginPage).forward(request, response);
                }
            } //</editor-fold>
            //====================================================================//
            //<editor-fold defaultstate="collapsed" desc="LOGOUT SECTOR">
            else if (action.equalsIgnoreCase("Logout")) {
                HttpSession session = request.getSession(true);
                session.invalidate();
                request.getRequestDispatcher(homepage).forward(request, response);
            } //</editor-fold>
            //====================================================================// 
            //<editor-fold defaultstate="collapsed" desc="REDIRECT REGISTER PAGE SECTOR">
            else if (action.equalsIgnoreCase("Register as new customer")) {
                request.getRequestDispatcher(registerPage).forward(request, response);
            } //</editor-fold>
            //====================================================================// 
            //<editor-fold defaultstate="collapsed" desc="REGISTER SECTOR">
            else if (action.equalsIgnoreCase("Register")) {
                String username = request.getParameter("txtUsername");
                String email = request.getParameter("txtEmail");
                String confirmEmail = request.getParameter("txtConfirmEmail");
                String password = request.getParameter("txtPassword");
                String confirmPassword = request.getParameter("txtConfirmPassword");
                String fullname = request.getParameter("txtFullname");
                String phone = request.getParameter("txtPhone");
                boolean tmp = true;
                User user = new User();
                UserDAO userDAO = new UserDAO();
                //Check user exist???
                user = userDAO.getUserByUsername(username);
                if (user != null) {
                    request.setAttribute("ERRORMESSAGE", "The Username exist!!!");
                    request.getRequestDispatcher(registerPage).forward(request, response);
                }
                if (username.equals("")) {
                    request.setAttribute("ERRORMESSAGE", "Username cannot blank!!!");
                    tmp = false;
                } else if (email.equals("")) {
                    request.setAttribute("ERRORMESSAGE", "Email cannot blank!!!");
                    tmp = false;
                } else if (!email.equals(confirmEmail)) {
                    request.setAttribute("ERRORMESSAGE", "Email and Confirm not equals!!!");
                    tmp = false;
                } else if (password.equals("")) {
                    request.setAttribute("ERRORMESSAGE", "Password cannot blank!!!");
                    tmp = false;
                } else if (!password.equals(confirmPassword)) {
                    request.setAttribute("ERRORMESSAGE", "Password and Confirm not equals!!!");
                    tmp = false;
                } else if (fullname.equals("")) {
                    request.setAttribute("ERRORMESSAGE", "Fullname cannot blank!!!");
                    tmp = false;
                } else if (phone.equals("")) {
                    request.setAttribute("ERRORMESSAGE", "Fullname cannot blank!!!");
                    tmp = false;
                }

                if (tmp) {
                    user = new User(username, password, email, fullname, phone, true, 2);
                    userDAO.registerUser(user);
                    request.setAttribute("USERNAME", username);
                    request.setAttribute("PASSWORD", password);
                    request.getRequestDispatcher(loginPage).forward(request, response);
                } else {
                    request.getRequestDispatcher(registerPage).forward(request, response);
                }
            } //</editor-fold>
            //====================================================================// 
            //<editor-fold defaultstate="collapsed" desc="ADD TO CART SECTOR">
            else if (action.equalsIgnoreCase("Add to Cart")) {
                HttpSession session = request.getSession();
                Cart cart = (Cart) session.getAttribute("CART");
                if (cart == null) {
                    cart = new Cart();
                }
                String bookID = request.getParameter("txtBookID");
                String quan = request.getParameter("ddlQuantity");
                int quantity = Integer.parseInt(quan);
                //Add many book into cart
                for (int i = 0; i < quantity; i++) {
                    cart.addItemToCart(bookID);
                }
                session.setAttribute("CART", cart);
                request.getRequestDispatcher(cartPage).forward(request, response);
            } //</editor-fold>
            //====================================================================// 
            //<editor-fold defaultstate="collapsed" desc="REMOVE ITEMS SECTOR">
            else if (action.equalsIgnoreCase("RemoveItems")) {
                String removeID = request.getParameter("removeBookID");
                HttpSession session = request.getSession(false);
                if (session != null) {
                    Cart cart = (Cart) session.getAttribute("CART");
                    if (cart != null) {
                        cart.removeItemFormCart(removeID);
                        //After remove check empty cart
                        boolean emptyCart = cart.checkEmptyHashMap();
                        if (emptyCart) {
                            //If Empty remove CART out of session
                            session.setAttribute("CART", null);
                        } else {
                            //Not empty set cart after remove to Session
                            session.setAttribute("CART", cart);
                        }
                    }
                }
                request.getRequestDispatcher(cartPage).forward(request, response);
            } //</editor-fold>
            //====================================================================// 
            //<editor-fold defaultstate="collapsed" desc="UPDATE ITEMS SECTOR">
            else if (action.equalsIgnoreCase("Update")) {
                String[] listBookID = request.getParameterValues("txtBookID");
                String[] listBookQuantity = request.getParameterValues("txtQuantity");
                int[] iLBookQuantity = new int[listBookID.length];

                HttpSession session = request.getSession(false);
                if (session != null) {
                    Cart cart = (Cart) session.getAttribute("CART");
                    if (cart != null) {
                        try {
                            for (int i = 0; i < listBookQuantity.length; i++) {
                                iLBookQuantity[i] = Integer.parseInt(listBookQuantity[i]);
                            }
                            for (int i = 0; i < listBookID.length; i++) {
                                cart.updateCart(listBookID[i], iLBookQuantity[i]);
                            }
                            //After update check empty cart
                            boolean emptyCart = cart.checkEmptyHashMap();
                            if (emptyCart) {
                                //If Empty remove CART out of session
                                session.setAttribute("CART", null);
                            } else {
                                //Not empty set cart after remove to Session
                                session.setAttribute("CART", cart);
                            }
                        } catch (NumberFormatException e) {
                            request.setAttribute("CARTERROR", "YES");
                        }
                    }
                }
                request.getRequestDispatcher(cartPage).forward(request, response);
            } //</editor-fold>
            //====================================================================// 
            //<editor-fold defaultstate="collapsed" desc="SEARCH SECTOR">
            else if (action.equalsIgnoreCase("Search")) {
                String keyWord = request.getParameter("txtSearch");
                BookDAO bDAO = new BookDAO();
                List<Book> searchByISBN = new ArrayList<Book>();
                List<Book> searchByTitle = new ArrayList<Book>();
                searchByTitle = bDAO.getBookByName(keyWord);
                searchByISBN = bDAO.getBookByISBN(keyWord);
                Set<Book> finalResult = new HashSet<Book>();
                finalResult.addAll(searchByTitle);
                finalResult.addAll(searchByISBN);
                HttpSession session = request.getSession();
                request.setAttribute("LISTBOOK", finalResult);
                request.setAttribute("SEARCHPIC", "Yes");
                request.setAttribute("QUANTITY", finalResult.size());
                request.getRequestDispatcher(searchResulPage).forward(request, response);
            } //</editor-fold>
            //====================================================================// 
            //<editor-fold defaultstate="collapsed" desc="CHECKOUT SECTOR">
            else if (action.equalsIgnoreCase("CheckOut")) {
                String process = request.getParameter("CheckOutProcess");
                if (process.equals("1")) {
                    //Buoc 1 qua trang Billing Page
                    request.getRequestDispatcher(ckOutBillingPage).forward(request, response);
                }
            } //</editor-fold>
            //====================================================================// 
            //<editor-fold defaultstate="collapsed" desc="PROCESS BILLING SECTOR">
            else if (action.equalsIgnoreCase("Continue")) {
                //Buoc 2 Check Out chuyen trang sang Delivery or Payment Page
                //Check process step
                String process = request.getParameter("continueType");
                if (process.equalsIgnoreCase("ToDelivery")) {
                    //Get parameters
                    boolean tmp = true;
                    String wantDelivery = request.getParameter("cbxDelivery");
                    String title = request.getParameter("ddlTitle");
                    String username = request.getParameter("txtUsername");
                    String fullname = request.getParameter("txtFullname");
                    String address = request.getParameter("txtAddress");
                    String town = request.getParameter("txtTown");
                    String county = request.getParameter("txtCounty");
                    String postcode = request.getParameter("txtPostcode");
                    String email = request.getParameter("txtEmail");
                    String phone = request.getParameter("txtPhone");
                    String country = request.getParameter("ddlCountry");
                    //Check blank
                    if (address.equals("")) {
                        request.setAttribute("BILLERROR", "Address cannot blank!!!");
                        tmp = false;
                    } else if (town.equals("")) {
                        request.setAttribute("BILLERROR", "Town cannot blank!!!");
                        tmp = false;
                    } else if (postcode.equals("")) {
                        request.setAttribute("BILLERROR", "Postcode cannot blank!!!");
                        tmp = false;
                    }
                    //Check error then process
                    if (tmp) {
                        Bill bill = new Bill();
                        bill.setTitle(title);
                        bill.setUsername(username);
                        bill.setFullname(fullname);
                        bill.setAddress(address);
                        bill.setTown(town);
                        bill.setCounty(county);
                        bill.setPostcode(postcode);
                        bill.setEmail(email);
                        bill.setPhone(phone);
                        bill.setCountry(country);
                        HttpSession session = request.getSession();
                        session.setAttribute("BILL", bill);

                        if (wantDelivery != null) {
                            request.getRequestDispatcher(ckOutDeliveryPage).forward(request, response);
                        } else {
                            request.getRequestDispatcher(ckOutPaymentgPage).forward(request, response);
                        }
                    } else {
                        request.getRequestDispatcher(ckOutBillingPage).forward(request, response);
                    }
                } else if (process.equalsIgnoreCase("ToPayment")) {
                    //Get parameters
                    boolean tmp = true;
                    String title = request.getParameter("ddlTitle");
                    String fullname = request.getParameter("txtRFullname");
                    String address = request.getParameter("txtRAddress");
                    String town = request.getParameter("txtRTown");
                    String county = request.getParameter("txtRCounty");
                    String postcode = request.getParameter("txtRPostcode");
                    String email = request.getParameter("txtREmail");
                    String country = request.getParameter("ddlCountry");
                    String phone = request.getParameter("txtRPhone");
                    //Check blank
                    if (fullname.equals("")) {
                        request.setAttribute("DELIERROR", "Fullname cannot blank!!!");
                        tmp = false;
                    } else if (address.equals("")) {
                        request.setAttribute("DELIERROR", "Address cannot blank!!!");
                        tmp = false;
                    } else if (town.equals("")) {
                        request.setAttribute("DELIERROR", "Town cannot blank!!!");
                        tmp = false;
                    } else if (postcode.equals("")) {
                        request.setAttribute("DELIERROR", "Postcode cannot blank!!!");
                        tmp = false;
                    } else if (email.equals("")) {
                        request.setAttribute("DELIERROR", "Email cannot blank!!!");
                        tmp = false;
                    } else if (phone.equals("")) {
                        request.setAttribute("DELIERROR", "Phone cannot blank!!!");
                        tmp = false;
                    }
                    //Check process and update bill
                    if (tmp) {
                        HttpSession session = request.getSession();
                        Bill bill = new Bill();
                        bill = (Bill) session.getAttribute("BILL");
                        bill.setRecipientTitle(title);
                        bill.setRecipientFullname(fullname);
                        bill.setRecipientAddress(address);
                        bill.setRecipientTown(town);
                        bill.setRecipientCounty(county);
                        bill.setRecipientPostcode(postcode);
                        bill.setRecipientEmail(email);
                        bill.setRecipientPhone(phone);
                        bill.setRecipientCountry(country);
                        session.setAttribute("BILL", bill);
                        request.getRequestDispatcher(ckOutPaymentgPage).forward(request, response);
                    } else {
                        request.getRequestDispatcher(ckOutDeliveryPage).forward(request, response);
                    }
                } else if (process.equalsIgnoreCase("ToConfirm")) {
                    HttpSession session = request.getSession();
                    Bill bill = new Bill();
                    bill = (Bill) session.getAttribute("BILL");
                    bill.setPaymentID(1);
                    bill.setShippingID(1);
                    float fsubTotal = (Float) session.getAttribute("SUBTOTAL");
                    double subTotal = fsubTotal;
                    bill.setSubtotal(subTotal);
                    bill.setTotal(subTotal);
                    session.setAttribute("BILL", bill);
                    request.getRequestDispatcher(ckOutConfirmPage).forward(request, response);
                }
            } //</editor-fold>
            //====================================================================// 
            //<editor-fold defaultstate="collapsed" desc="CONFIRM BILLING SECTOR">
            else if (action.equalsIgnoreCase("Confirm")) {
                HttpSession session = request.getSession(false);
                if (session != null) {
                    Cart cart = (Cart) session.getAttribute("CART");
                    if (cart != null) {
                        HashMap items = cart.getItems();
                        if (!items.isEmpty()) {
                            Iterator iter = items.entrySet().iterator();
                            Order order = new Order();
                            List<OrderDetail> odList = new ArrayList<OrderDetail>();
                            while (iter.hasNext()) {
                                Map.Entry item = (Entry) iter.next();
                                BookDAO bDAO = new BookDAO();
                                Book book = bDAO.getBookByBookID(item.getKey().toString());
                                if (book != null) {
                                    int quantity = (Integer) item.getValue();
                                    OrderDetail od = new OrderDetail();
                                    od.setBookID(book.getBookID());
                                    od.setQuantity(quantity);
                                    String sBookPrice = book.getBookPrice();
                                    double dBookPrice = Double.parseDouble(sBookPrice.substring(1, sBookPrice.length()));
                                    double total = quantity * dBookPrice;
                                    od.setSubPrice(total);
                                    od.setUnitPrice(dBookPrice);
                                    odList.add(od);
                                }
                            }
                            //SET INFO FOR ORDER
                            float fsubTotal = (Float) session.getAttribute("SUBTOTAL");
                            double subTotal = fsubTotal;
                            User user = (User) session.getAttribute("USER");
                            String username = user.getUsername();
                            Date insertDate = new Date();
                            Timestamp bookingDate = new Timestamp(insertDate.getTime());
                            order.setBookingTime(bookingDate);
                            order.setTotalPrice(subTotal);
                            order.setUsername(username);
                            //Mac dinh cac order cho staff xu ly
                            order.setStatusID(1);
                            //INSERT ORDER INTO DATABASE
                            OrderDAO oDAO = new OrderDAO();
                            OrderDetailDAO odDAO = new OrderDetailDAO();

                            oDAO.insertOrder(order);

                            int orderID = oDAO.getLastOrderID();
                            System.out.println(orderID);

                            //SET ORDER ID FOR ORDER DETAIL LIST
                            for (OrderDetail od : odList) {
                                od.setOrderID(orderID);
                                //INSERT ORDERDETAIL INTO DB
                                odDAO.insertOrderDetail(od);
                            }

                            //INSERT BILL INTO DATABASE
                            Bill bill = (Bill) session.getAttribute("BILL");
                            bill.setOrderBillID(orderID);
                            BillDAO billDAO = new BillDAO();
                            billDAO.insertBill(bill);
                            //HUY SESSION KO CAN THIET
                            session.removeAttribute("SUBTOTAL");
                            session.removeAttribute("CART");
                            session.removeAttribute("BILL");
                            session.removeAttribute("SUMQUANTITY");
                        }
                    }
                }
                request.getRequestDispatcher(homepage).forward(request, response);
            } //</editor-fold>
            //====================================================================// 
            //<editor-fold defaultstate="collapsed" desc="VIEW ORDER SECTOR">
            else if (action.equalsIgnoreCase("ViewAllOrder")) {
                String username = request.getParameter("txtUsername");
                if (username.equals("")) {
                    request.getRequestDispatcher(homepage).forward(request, response);
                } else {
                    UserDAO uDAO = new UserDAO();
                    User user = new User();
                    user = uDAO.getUserByUsername(username);
                    if (user != null) {
                        if (user.getRoleID() == 1) {
                            //User is staff
                            List<Order> orderList = new ArrayList<Order>();
                            OrderDAO oDAO = new OrderDAO();

                            Calendar cal = Calendar.getInstance();
                            java.util.Date uD = new java.util.Date();
                            java.sql.Date dateTo = new java.sql.Date(uD.getTime());
                            cal.setTime(dateTo);
                            cal.add(Calendar.DATE, 1);
                            uD = (java.util.Date) cal.getTime();
                            dateTo = new java.sql.Date(uD.getTime());
                            cal.add(Calendar.DATE, -8);
                            java.util.Date sDF = (java.util.Date) cal.getTime();
                            java.sql.Date dateFrom = new java.sql.Date(sDF.getTime());
                            System.out.println(dateFrom + " - " + dateTo);

                            orderList = oDAO.getOrderByInWeek(dateFrom, dateTo);
//                            HttpSession session = request.getSession();
                            request.setAttribute("ORDERLIST", orderList);
                            request.getRequestDispatcher(viewOrderPage).forward(request, response);
                        } else if (user.getRoleID() == 2) {
                            //User is customer
                            //Get all order of this user then marshall into xml
                            //Using this xml with xsl to be an jsp
                            List<Order> orderList = new ArrayList<Order>();
                            OrderDAO oDAO = new OrderDAO();
                            orderList = oDAO.getOrderByUsername(username);

                            JAXBMarshall jm = new JAXBMarshall();
                            jm.marshallOrder(orderList);
                            request.getRequestDispatcher(viewOrderPage).forward(request, response);
                        }
                    }
                }
            } //</editor-fold>
            //====================================================================// 
            //<editor-fold defaultstate="collapsed" desc="PRODUCT DETAIL SECTOR">
            else if (action.equalsIgnoreCase("ProductDetail")) {
                String bookID = request.getParameter("productID");
                Book book = new Book();
                BookDAO bDAO = new BookDAO();
                book = bDAO.getBookByBookID(bookID);
                if (book != null) {
                    System.out.println(book);

                    List<String> listString = new ArrayList<String>();
                    String[] lString = book.getBookDescription().split(";");

                    listString.addAll(Arrays.asList(lString));
                    request.setAttribute("BOOKDETAIL", book);
                    request.setAttribute("BOOKDESCRIPTION", listString);

                    request.getRequestDispatcher(productDetailPage).forward(request, response);
                }

            } //</editor-fold>
            //====================================================================// 
            //<editor-fold defaultstate="collapsed" desc="GET CATEGORY SECTOR">
            else if (action.equalsIgnoreCase("GetCategory")) {
                String categoryID = request.getParameter("categoryID");
                BookDAO bDAO = new BookDAO();
                List<Book> result = bDAO.getBookByCategoryID(categoryID);
                request.setAttribute("LISTBOOK", result);
                request.setAttribute("QUANTITY", result.size());
                if (categoryID.equals("C0002")) {
                    request.setAttribute("CATE01", "Yes");
                } else if (categoryID.equals("C0003")) {
                    request.setAttribute("CATE02", "Yes");
                } else if (categoryID.equals("C0004")) {
                    request.setAttribute("CATE03", "Yes");
                } else if (categoryID.equals("C0005")) {
                    request.setAttribute("CATE04", "Yes");
                }
                request.getRequestDispatcher(searchResulPage).forward(request, response);
            } //</editor-fold>
            //====================================================================// 
            //<editor-fold defaultstate="collapsed" desc="STAFF GET CATEGORY SECTOR">
            else if (action.equalsIgnoreCase("StaffGetCategory")) {
                /*THIS SECTION USING XML TECHNOLOGY*/
                String categoryID = request.getParameter("categoryID");
                System.out.println(categoryID);
                if (categoryID.equals("C0002")) {
                    request.setAttribute("CATE01", "Yes");
                } else if (categoryID.equals("C0003")) {
                    request.setAttribute("CATE02", "Yes");
                } else if (categoryID.equals("C0004")) {
                    request.setAttribute("CATE03", "Yes");
                } else if (categoryID.equals("C0005")) {
                    request.setAttribute("CATE04", "Yes");
                }
                System.out.println("STARTING");

                //USING STAX TO SEARCH 
                StAXParserAPI parser = new StAXParserAPI();
                List<Book> result = new ArrayList<Book>();
                result = parser.searchBookInXMLFile(categoryID);
                request.setAttribute("LISTBOOK", result);
                request.setAttribute("QUANTITY", result.size());

                request.getRequestDispatcher(searchResulPage).forward(request, response);
            } //</editor-fold>
            //====================================================================// 
            //<editor-fold defaultstate="collapsed" desc="ADD BOOK SECTOR">
            else if (action.equalsIgnoreCase("Add")) {
                boolean tmp = true;
                boolean check = true;

                String bookName = request.getParameter("txtBookName");
                String categoryName = request.getParameter("ddlCategory");
                String bookPrice = request.getParameter("txtPrice");
                String bookPages = request.getParameter("txtPages");
                String bookFormat = request.getParameter("txtFormat");
                String bookAuthor = request.getParameter("txtAuthor");
                String bookISBN = request.getParameter("txtISBN");
                String bookDetailedEdition = request.getParameter("txtDetailedEdition");
                String bookDescription = request.getParameter("txtDescription");

                if (bookName.equals("") || categoryName.equals("")
                        || bookPrice.equals("") || bookPages.equals("")
                        || bookFormat.equals("") || bookAuthor.equals("")
                        || bookISBN.equals("") || bookDetailedEdition.equals("")
                        || bookDescription.equals("")) {
                    tmp = false;
                    request.setAttribute("ERRORMESSAGE", "yes");
                }
                //Ko co field nao blank thi xu ly tiep
                if (tmp) {
                    CategoryDAO cDAO = new CategoryDAO();
                    String categoryID = cDAO.getCategoryIDByName(categoryName);
                    String bookID = "1405";
                    String bookThumb = "http://images.harpercollins.co.uk/hcwebimages/hccovers/038100/038102-fc50.jpg";
                    String bookImg = "http://www.tolkien.co.uk/file/IfbTdA8/04320010-300a-4019-a2e9-1b66cb3f3218.jpg";
                    String bookLink = "http://www.tolkien.co.uk/product/9780007252244/The+Children+of+H%c3%barin+";

                    Calendar cal = Calendar.getInstance();
                    System.out.println(new SimpleDateFormat("MM").format(cal.getTime()));
                    String day = new SimpleDateFormat("dd").format(cal.getTime());
                    String month = new SimpleDateFormat("MM").format(cal.getTime());
                    String year = new SimpleDateFormat("yyyy").format(cal.getTime());
                    String bookPublishedDate = day + "/" + month + "/" + year;

                    personal.adding.Book addingBook = new personal.adding.Book();
                    addingBook.setBookID(bookID);
                    addingBook.setCategoryID(categoryID);
                    addingBook.setBookAuthor(bookAuthor);
                    addingBook.setBookDescription(bookDescription);
                    addingBook.setBookFormat(bookFormat);
                    addingBook.setBookISBN(bookISBN);
                    addingBook.setBookImg(bookImg);
                    addingBook.setBookLink(bookLink);
                    addingBook.setBookName(bookName);
                    addingBook.setBookPages(bookPages);
                    addingBook.setBookPrice(bookPrice);
                    addingBook.setBookPublishedDate(bookPublishedDate);
                    addingBook.setBookThumb(bookThumb);
                    addingBook.setBookDetailedEdition(bookDetailedEdition);

                    //Marshall adding book info into xml file
                    JAXBMarshall jm = new JAXBMarshall();
                    jm.marshallAddingBook(addingBook);

                    //CHECK VALIDATION CHO THONG TIN VUA DUOC ADD
                    personal.validation.Book items = null;
                    try {
                        //CHECK VALIDATION USING SCHEMA - SAX PARSER
                        JAXBContext jc = JAXBContext.newInstance("personal.validation");
                        Unmarshaller u = jc.createUnmarshaller();

                        u.setEventHandler(new JAXBBookValidationHandler());
                        SchemaFactory sf = SchemaFactory.newInstance(
                                XMLConstants.W3C_XML_SCHEMA_NS_URI);
                        Schema schema = sf.newSchema(new File("C:\\Users\\TruongHoangLe\\Desktop\\XML Project\\XML_Project\\web\\xml\\bookValidation.xsd"));

                        u.setSchema(schema);

                        System.out.println("======");
                        File f = new File("C:\\Users\\TruongHoangLe\\Desktop\\XML Project\\XML_Project\\web\\xml\\addingBook.xml");
                        items = (personal.validation.Book) u.unmarshal(f);
                    } catch (JAXBException e) {
                        check = false;//Check info have errors
                        request.setAttribute("ERRORMESSAGE", "yes");
                        e.printStackTrace();
                    } catch (Exception e) {
                        check = false;//Check info have errors
                        request.setAttribute("ERRORMESSAGE", "yes");
                        e.printStackTrace();
                    }
                    try {

                    } catch (Exception e) {
                        request.setAttribute("ERRORMESSAGE", "yes");
                    }
                    String sPrice = String.valueOf(items.getBookPrice());
                    String first = sPrice.substring(0, 1);
                    String sPage = "";
                    String fPage = "";
                    if (items.getBookPages() != null) {
                        sPage = items.getBookPages().toString();
                        fPage = sPage.substring(0, 1);
                    } else {
                        check = false;
                        request.setAttribute("ERRORMESSAGE", "yes");
                    }

                    if (items.getBookPages() == null) {
                        check = false;
                        request.setAttribute("ERRORMESSAGE", "yes");
                    } else if (!first.matches("^[0-9]")) {
                        check = false;
                        request.setAttribute("ERRORMESSAGE", "yes");
                    } else if (!(first.equals("1") || first.equals("2")
                            || first.equals("3") || first.equals("4")
                            || first.equals("5") || first.equals("6")
                            || first.equals("7") || first.equals("8")
                            || first.equals("9"))) {
                        check = false;
                        request.setAttribute("ERRORMESSAGE", "yes");
                    } else if (!(fPage.equals("1") || fPage.equals("2")
                            || fPage.equals("3") || fPage.equals("4")
                            || fPage.equals("5") || fPage.equals("6")
                            || fPage.equals("7") || fPage.equals("8")
                            || fPage.equals("9"))) {
                        check = false;
                        request.setAttribute("ERRORMESSAGE", "yes");
                    }
                    //Check xem thong tin co validation ko?
                    if (check) {
                        //Neu info validation thi tien hanh insert vao database
                        //Transfer data
                        Utility utility = new Utility();
                        personal.obj.Book book = utility.transferBookType(items);
                        BookDAO bDAO = new BookDAO();
                        bDAO.insertNewBook(book);
                        //Re-load all book from db to XML
                        jm.marshallAllBook();
                        jm.marshallAllBookPDF();
                        request.getRequestDispatcher(homepage).forward(request, response);
                    } else {
                        request.getRequestDispatcher(addNewBookPage).forward(request, response);
                    }
                } else {
                    request.getRequestDispatcher(addNewBookPage).forward(request, response);
                }

            } //</editor-fold>
            //====================================================================// 
            //<editor-fold defaultstate="collapsed" desc="PROCESS ORDER SECTOR">
            else if (action.equalsIgnoreCase("Process")) {
                String orderIDS = request.getParameter("orderID");
                try {
                    int iOrderID = Integer.parseInt(orderIDS);
                    OrderDAO oDAO = new OrderDAO();
                    oDAO.processOrder(iOrderID);
                    //Re-load list
                    Calendar cal = Calendar.getInstance();
                    java.util.Date uD = new java.util.Date();
                    java.sql.Date dateTo = new java.sql.Date(uD.getTime());
                    cal.setTime(dateTo);
                    cal.add(Calendar.DATE, 1);
                    uD = (java.util.Date) cal.getTime();
                    dateTo = new java.sql.Date(uD.getTime());
                    cal.add(Calendar.DATE, -8);
                    java.util.Date sDF = (java.util.Date) cal.getTime();
                    java.sql.Date dateFrom = new java.sql.Date(sDF.getTime());
                    System.out.println(dateFrom + " - " + dateTo);
                    List<Order> orderList = new ArrayList<Order>();
                    orderList = oDAO.getOrderByInWeek(dateFrom, dateTo);
//                    HttpSession session = request.getSession();
                    request.setAttribute("ORDERLIST", orderList);
                    request.getRequestDispatcher(viewOrderPage).forward(request, response);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } //</editor-fold>
            //====================================================================// 
            //<editor-fold defaultstate="collapsed" desc="ORDER DETAIL SECTOR">
            else if (action.equalsIgnoreCase("Detail")) {
                try {
                    String txtOrderID = request.getParameter("txtOrderID");
                    int orderID = Integer.parseInt(txtOrderID);
                    //GET ALL ORDER DETAIL INFO
                    List<OrderDetail> orderDetails = new ArrayList<OrderDetail>();
                    OrderDetailDAO odDAO = new OrderDetailDAO();
                    orderDetails = odDAO.getOrderDetailByOrderID(orderID);
                    //GET BILL INFO OF THIS ORDER
                    Bill bill = new Bill();
                    BillDAO biDAO = new BillDAO();
                    bill = biDAO.getBillByID(orderID);
                    //SET TO REQUEST
                    request.setAttribute("ORDERDETAILLIST", orderDetails);
                    request.setAttribute("BILL", bill);
                    request.getRequestDispatcher(viewOrderDetail).forward(request, response);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } //</editor-fold>
            //====================================================================// 
            //<editor-fold defaultstate="collapsed" desc="PDF DOWNLOAD SECTOR">
            else if (action.equals("Download")) {
                String path = getServletContext().getRealPath("/");
                String xslPath = path + "/WEB-INF/bookFO.xsl";
                String xmlPath = path + "/WEB-INF/books.xml";
                String foPath = path + "/WEB-INF/books.fo";
                methodTrAX(xslPath, xmlPath, foPath, path);
                File file = new File(foPath);
                FileInputStream input = new FileInputStream(file);
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                response.setContentType("application/pdf");
                FopFactory ff = FopFactory.newInstance();
                FOUserAgent fua = ff.newFOUserAgent();
                Fop fop = ff.newFop(MimeConstants.MIME_PDF, fua, out);
                TransformerFactory tff = TransformerFactory.newInstance();
                Transformer trans = tff.newTransformer();
                File fo = new File(foPath);
                Source src = new StreamSource(fo);
                Result result = new SAXResult(fop.getDefaultHandler());
                trans.transform(src, result);
                byte[] content = out.toByteArray();
                response.setContentLength(content.length);
                response.getOutputStream().write(content);
                response.getOutputStream().flush();
            } //</editor-fold>
            //====================================================================// 

        } finally {
//            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (SAXException ex) {
            Logger.getLogger(ProcessServlet.class.getName()).log(Level.SEVERE, null, ex);
        } catch (TransformerException ex) {
            Logger.getLogger(ProcessServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (SAXException ex) {
            Logger.getLogger(ProcessServlet.class.getName()).log(Level.SEVERE, null, ex);
        } catch (TransformerException ex) {
            Logger.getLogger(ProcessServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    public static void methodTrAX(String xslPath, String xmlPath, String output, String path) {
        try {
            TransformerFactory tf = TransformerFactory.newInstance();
            StreamSource xsltFile = new StreamSource(xslPath);
            Transformer trans = tf.newTransformer(xsltFile);

            StreamSource xmlFile = new StreamSource(xmlPath);
            StreamResult htmlFile = new StreamResult(new FileOutputStream(output));
            trans.transform(xmlFile, htmlFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
